<?php

// TODO check cookie sending.


/**
 * File Description
 * 
 * Kao: PHP Web Framework <http://www.byhuy.com/kao/>.
 * Copyright 2007-2008, Huy Nguyen <http://www.byhuy.com/>.
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 * 
 */

class Kao_App_Response
{
    
    /**
     * List of all known HTTP response codes
     *
     * "Borrowed" from Zend Framework (Zend_Http_Response)
     * @var array
     */
    protected static $messages = array(
        // Informational 1xx
        100 => 'Continue',
        101 => 'Switching Protocols',

        // Success 2xx
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',

        // Redirection 3xx
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',  // 1.1
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        // 306 is deprecated but reserved
        307 => 'Temporary Redirect',

        // Client Error 4xx
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',

        // Server Error 5xx
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        509 => 'Bandwidth Limit Exceeded'
    );
    
    
    protected $_responseCode = 200;
    
    /**
     * Cookie
     */
    protected $_cookies = array();
    
    /**
     * Headers (except Cookies)
     */
    protected $_headers = array();
    
    /**
     * Response body
     */
    protected $_body = array();
    
    /**
     * True if the body was output
     */
    protected $_bodyOutput = false;
    
    
    public function __construct()
    {
        
    }
    
    public function setCookies($name, $value = '', $expire = null, $path = null, $domain = null, $secure = false, $httponly = false)
    {
        $this->_cookies[$name] = array(
            'value'    => $value,
            'expire'   => $expire,
            'path'     => $path,
            'domain'   => $domain,
            'secure'   => $secure,
            'httponly' => $httponly,
        );
    }
    
    /**
     * Sends set cookies to client.
     */
    public function sendCookies()
    {
        foreach ($this->_cookies as $name => $jar)
        {
            setcookie($name, $jar['value'], $jar['expire'], $jar['path'], $jar['domain'], $jar['secure'], $jar['httponly']);
        }
    }
    
    /**
     * Clears set cookies
     */
    public function clearCookies()
    {
        $this->_cookies = array();
        return $this;
    }
    
    public function getCookies()
    {
        return $this->_cookies;
    }
    
    /**
     * Sets a header
     * 
     * @param string $header
     * @param boolean 
     */
    public function setHeader($header, $flush = false, $replace = true)
    {
        if ($flush === true)
        {
            if (!$this->canSendHeaders())
            {
                $this->_throwHeadersSentException();
            }
            header($header, $replace);
            return;
        }
        $this->_headers[] = array('header' => $header, 'replace' => $replace);
        return $this;
    }
    
    
    /**
     * Sends set headers to client
     * 
     * @param boolean $sendCookie
     */
    public function sendHeaders($sendCookie = true)
    {
        if (!$this->canSendHeaders())
        {
            $this->_throwHeadersSentException();
        }
        
        foreach ($this->_headers as $header)
        {
            header($header['header'], $header['replace']);
        }
        
        if ($sendCookie)
        {
            $this->sendCookies();
        }
        $this->_headers = array();
        return $this;
    }
    
    
    public function headersSent()
    {
        return headers_sent();
    }
    
    /**
     * Returns true if it's able to send the headers to client
     */
    public function canSendHeaders()
    {
        return !$this->_bodyOutput;
    }
    
    /**
     * Clears set headers
     */
    public function clearHeaders()
    {
        $this->_headers = array();
        return $this;
    }
    
    /**
     * Gets all set headers
     */
    public function getHeaders()
    {
        $return = array();
        foreach ($this->_headers as $header)
        {
            $return[] = $header['header'];
        }
        return $return;
    }
    
    /**
     * Sets the response body
     */
    public function setBody($body)
    {
        $this->_body = $body;
        return $this;
    }
    
    /**
     * Append a body segment
     */
    /*public function appendBody($name, $body = '')
    {
        if (!isset($this->_bodySegments[$name]))
        {
            $this->_bodySegments[$name] = $body;
            return;
        }
        $this->_bodySegments[$name] .= $body;
        return $this;
    }*/
    
    /**
     * Set HTTP response code
     * 
     * @param int $code
     */
    public function setResponseCode($code)
    {
        if (!is_int($code) || !isset(self::$messages[$code]))
        {
            require_once 'Kao/App/Response/Exception.php';
            throw new Kao_App_Response_Exception();
        }
        $this->_responseCode = $code;
        return $this;
    }
    
    /**
     * Returns HTTP response code
     */
    public function getResponseCode()
    {
        return $this->_responseCode;
    }
    
    /**
     * Sends HTTP response code with message
     * 
     * @param int code 
     */
    public function sendResponseCode($code = null)
    {
        if (null !== $code)
        {
            $this->setResponseCode($code);
        }
        // TODO allow customise HTTP version
        header('HTTP/1.x ' . self::$messages[$code]);
        return $this;
    }
    
    /**
     * Set redirect HTTP header
     * 
     * @param string $url
     * @param boolean $flush
     * @param int $code
     */
    public function setRedirect($url, $flush = false, $code = 302)
    {
        if (!$this->canSendHeaders())
        {
            $this->_throwHeadersSentException();
        }
        
        $this->sendResponseCode($code)->setHeader('Location: ' . $url, $flush);
    }
    
    /**
     * Throws exception
     */
    protected function _throwHeadersSentException()
    {
        headers_sent($file, $line);
        require_once 'Kao/App/Response/Exception.php';
        throw new Kao_App_Response_Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
    }
    
    /**
     * Returns response body
     */
    public function getBody()
    {
        return $this->_body;
    }
    
    public function __toString()
    {
        // sends custom response code if it's different than 200
        if ($this->_responseCode != 200)
        {
            $this->sendResponseCode();
        }
        if (!$this->headersSent())
        {
            $this->sendHeaders();
        }
        echo $this->getBody();
    }
}

